package com.vehicle.core.rest;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableSet;
import com.vehicle.core.dto.Result;
import com.vehicle.core.exception.ExceptionConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Date;


/**
 * @author shouhan
 * @version 1.0
 * @date 2018/12/28
 * @desc 全局返回值
 * @see
 * @since 1.0
 */
@ControllerAdvice
public class BaseGlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final Logger logger = LoggerFactory.getLogger(BaseGlobalResponseBodyAdvice.class);

    /**
     * swagger请求地址返回不需要处理
     */
    private final ImmutableSet<String> URI_EXCLUDE_SET = new ImmutableSet.Builder<String>()
            .add("/app/swagger-resources")
            .add("/app/v2/api-docs")
            .build();


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //开启自定义全局数据处理 返回值设置为：true；
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (URI_EXCLUDE_SET.contains(((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getRequestURI())) {
            return obj;
        }
        if (obj == null || !(obj instanceof Result)) {
            Result result = new Result(ExceptionConstants.SUCCESS, obj);
            result.setServerTime(new Date());
            //String类型单独处理
            if (obj instanceof String) {
                return JSON.toJSONString(result);
            }
            return result;
        }
        return obj;
    }

}